<template>
  <div class="videos-container">
    <div class="page-header">
      <h2>视频管理</h2>
      <el-button type="primary" @click="handleAdd">上传视频</el-button>
    </div>

    <!-- 搜索和过滤 -->
    <div class="search-bar">
      <el-form :inline="true" :model="searchForm">
        <el-form-item label="标题">
          <el-input v-model="searchForm.title" placeholder="请输入视频标题" clearable />
        </el-form-item>
        <el-form-item label="上传者">
          <el-input v-model="searchForm.uploader" placeholder="请输入上传者" clearable />
        </el-form-item>
        <el-form-item label="上传时间">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 视频列表 -->
    <el-table :data="videoList" border style="width: 100%">
      <el-table-column prop="video_id" label="ID" width="80" />
      <el-table-column label="封面" width="120">
        <template #default="{ row }">
          <el-image 
            :src="row.cover_image" 
            :preview-src-list="[row.cover_image]"
            fit="cover"
            style="width: 100px; height: 60px"
          >
            <template #error>
              <div class="image-placeholder">暂无封面</div>
            </template>
          </el-image>
        </template>
      </el-table-column>
      <el-table-column prop="title" label="标题" min-width="200" show-overflow-tooltip />
      <el-table-column prop="duration" label="时长" width="100">
        <template #default="{ row }">
          {{ formatDuration(row.duration) }}
        </template>
      </el-table-column>
      <el-table-column prop="play_count" label="播放量" width="100" />
      <el-table-column prop="like_count" label="点赞数" width="100" />
      <el-table-column prop="comment_count" label="评论数" width="100" />
      <el-table-column prop="upload_time" label="上传时间" width="180" />
      <el-table-column label="操作" width="250" fixed="right">
        <template #default="{ row }">
          <el-button size="small" @click="handleView(row)">预览</el-button>
          <el-button size="small" type="primary" @click="handleEdit(row)">编辑</el-button>
          <el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 预览视频对话框 -->
    <el-dialog v-model="viewDialogVisible" title="视频预览" width="800px">
      <div class="video-player">
        <video 
          :src="currentVideo.url" 
          controls 
          style="width: 100%"
          v-if="currentVideo.url"
        ></video>
      </div>
      <el-descriptions :column="2" border class="mt-20">
        <el-descriptions-item label="视频ID">{{ currentVideo.video_id }}</el-descriptions-item>
        <el-descriptions-item label="标题">{{ currentVideo.title }}</el-descriptions-item>
        <el-descriptions-item label="时长">{{ formatDuration(currentVideo.duration) }}</el-descriptions-item>
        <el-descriptions-item label="播放量">{{ currentVideo.play_count }}</el-descriptions-item>
        <el-descriptions-item label="点赞数">{{ currentVideo.like_count }}</el-descriptions-item>
        <el-descriptions-item label="评论数">{{ currentVideo.comment_count }}</el-descriptions-item>
        <el-descriptions-item label="上传时间">{{ currentVideo.upload_time }}</el-descriptions-item>
        <el-descriptions-item label="上传者">{{ currentVideo.uploader_id }}</el-descriptions-item>
        <el-descriptions-item label="描述" :span="2">{{ currentVideo.description }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>

    <!-- 编辑/上传视频对话框 -->
    <el-dialog
      v-model="editDialogVisible"
      :title="isEdit ? '编辑视频' : '上传视频'"
      width="600px"
    >
      <el-form :model="editForm" :rules="rules" ref="editFormRef" label-width="100px">
        <el-form-item label="视频文件" prop="url" v-if="!isEdit">
          <el-upload
            class="video-upload"
            action="#"
            :auto-upload="false"
            :on-change="handleVideoChange"
            accept="video/*"
          >
            <template #trigger>
              <el-button type="primary">选择视频</el-button>
            </template>
            <template #tip>
              <div class="el-upload__tip">支持mp4、mov等主流视频格式</div>
            </template>
          </el-upload>
        </el-form-item>
        <el-form-item label="视频封面" prop="cover_image">
          <el-upload
            class="cover-upload"
            action="#"
            :auto-upload="false"
            :on-change="handleCoverChange"
            accept="image/*"
          >
            <template #trigger>
              <el-button type="primary">选择封面</el-button>
            </template>
            <template #tip>
              <div class="el-upload__tip">建议尺寸 16:9，支持jpg、png格式</div>
            </template>
          </el-upload>
        </el-form-item>
        <el-form-item label="标题" prop="title">
          <el-input v-model="editForm.title" placeholder="请输入视频标题" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input 
            type="textarea" 
            v-model="editForm.description" 
            rows="4"
            placeholder="请输入视频描述"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSave">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 搜索表单
const searchForm = ref({
  title: '',
  uploader: '',
  dateRange: []
})

// 视频列表数据
const videoList = ref([
  {
    video_id: 1,
    url: 'https://example.com/video1.mp4',
    title: '健康运动指南',
    description: '专业教练教你正确的运动方式',
    cover_image: 'https://example.com/cover1.jpg',
    duration: 1800,
    uploader_id: 1,
    upload_time: '2024-12-15 10:00:00',
    play_count: 1500,
    like_count: 200,
    comment_count: 50,
    favorite_count: 100
  },
  {
    video_id: 2,
    url: 'https://example.com/video2.mp4',
    title: '每日瑜伽课程',
    description: '15分钟快速瑜伽教程',
    cover_image: 'https://example.com/cover2.jpg',
    duration: 900,
    uploader_id: 2,
    upload_time: '2024-12-16 14:30:00',
    play_count: 2000,
    like_count: 300,
    comment_count: 80,
    favorite_count: 150
  },
  {
    video_id: 3,
    url: 'https://example.com/video3.mp4',
    title: '营养健康讲座',
    description: '专业营养师分享健康饮食知识',
    cover_image: 'https://example.com/cover3.jpg',
    duration: 3600,
    uploader_id: 3,
    upload_time: '2024-12-17 16:20:00',
    play_count: 1200,
    like_count: 180,
    comment_count: 40,
    favorite_count: 90
  }
])

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(3)

// 对话框相关
const viewDialogVisible = ref(false)
const editDialogVisible = ref(false)
const isEdit = ref(false)
const currentVideo = ref({})
const editFormRef = ref(null)

// 表单校验规则
const rules = {
  title: [
    { required: true, message: '请输入视频标题', trigger: 'blur' },
    { min: 2, max: 100, message: '长度在 2 到 100 个字符', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入视频描述', trigger: 'blur' }
  ]
}

// 编辑表单
const editForm = ref({
  title: '',
  description: '',
  url: '',
  cover_image: ''
})

// 格式化视频时长
const formatDuration = (seconds) => {
  const hours = Math.floor(seconds / 3600)
  const minutes = Math.floor((seconds % 3600) / 60)
  const remainingSeconds = seconds % 60
  
  if (hours > 0) {
    return `${hours}:${minutes.toString().padStart(2, '0')}:${remainingSeconds.toString().padStart(2, '0')}`
  }
  return `${minutes}:${remainingSeconds.toString().padStart(2, '0')}`
}

// 搜索处理
const handleSearch = () => {
  // TODO: 实现搜索逻辑
  console.log('搜索条件:', searchForm.value)
}

// 重置搜索
const resetSearch = () => {
  searchForm.value = {
    title: '',
    uploader: '',
    dateRange: []
  }
  handleSearch()
}

// 预览视频
const handleView = (row) => {
  currentVideo.value = { ...row }
  viewDialogVisible.value = true
}

// 上传视频
const handleAdd = () => {
  isEdit.value = false
  editForm.value = {
    title: '',
    description: '',
    url: '',
    cover_image: ''
  }
  editDialogVisible.value = true
}

// 编辑视频
const handleEdit = (row) => {
  isEdit.value = true
  editForm.value = { ...row }
  editDialogVisible.value = true
}

// 删除视频
const handleDelete = (row) => {
  ElMessageBox.confirm(
    `确定要删除视频 "${row.title}" 吗？`,
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    // TODO: 实现删除逻辑
    ElMessage.success('删除成功')
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

// 视频文件改变
const handleVideoChange = (file) => {
  // TODO: 处理视频文件上传
  console.log('选择的视频文件:', file)
}

// 封面图片改变
const handleCoverChange = (file) => {
  // TODO: 处理封面图片上传
  console.log('选择的封面图片:', file)
}

// 保存视频
const handleSave = () => {
  editFormRef.value?.validate((valid) => {
    if (valid) {
      // TODO: 实现保存逻辑
      ElMessage.success(isEdit.value ? '编辑成功' : '上传成功')
      editDialogVisible.value = false
    }
  })
}

// 分页大小改变
const handleSizeChange = (val) => {
  pageSize.value = val
  // TODO: 重新加载数据
}

// 当前页改变
const handleCurrentChange = (val) => {
  currentPage.value = val
  // TODO: 重新加载数据
}
</script>

<style scoped>
.videos-container {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-bar {
  margin-bottom: 20px;
  padding: 20px;
  background: #fff;
  border-radius: 4px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.image-placeholder {
  width: 100px;
  height: 60px;
  background: #f5f7fa;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #909399;
  font-size: 12px;
}

.video-player {
  width: 100%;
  background: #000;
  aspect-ratio: 16/9;
  display: flex;
  align-items: center;
  justify-content: center;
}

.mt-20 {
  margin-top: 20px;
}

.video-upload,
.cover-upload {
  :deep(.el-upload-list) {
    width: 100%;
  }
}
</style> 